package cn.edu.sdjzu.xg.eagle.service;

import cn.edu.sdjzu.xg.eagle.dao.DepartmentImpel;
import cn.edu.sdjzu.xg.eagle.dao.SchoolDaoImpl;
import cn.edu.sdjzu.xg.eagle.entity.Pagination;
import cn.edu.sdjzu.xg.eagle.entity.School;
import cn.edu.sdjzu.xg.eagle.exception.BysjException;
import cn.edu.sdjzu.xg.eagle.factory.DaoFactory;
import cn.edu.sdjzu.xg.eagle.util.JdbcHelper;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Collection;


public class SchoolServiceImpl implements SchoolServiceInterface {
    private static final SchoolServiceImpl schoolServiceImpl = new SchoolServiceImpl();
    SchoolDaoImpl schoolDaoImpl = DaoFactory.getDao(SchoolDaoImpl.class,"SchoolDaoImpl");
    public SchoolServiceImpl() {}

    public static SchoolServiceImpl getInstance() {

        return schoolServiceImpl;
    }
    @Override
    public Collection<School> findAll() throws SQLException, BysjException {
        return SchoolDaoImpl.getInstance().findAll();
    }

    @Override
    public Collection<School> findAll(Pagination pagination) throws SQLException, BysjException {
        return SchoolDaoImpl.getInstance().findAll();
    }

    @Override
    public School find(Long id) throws SQLException, BysjException {
        return SchoolDaoImpl.getInstance().find(id);
    }

    @Override
    public boolean delete(Long id) throws SQLException, BysjException {
        School school = SchoolDaoImpl.getInstance().find(id);
        int countDepartsOfSchool = DepartmentImpel.getInstance().countAll(school);
        if (countDepartsOfSchool == 0) {
            return SchoolDaoImpl.getInstance().delete(id);
        }else{
            throw new BysjException(school.getDescription()+"仍然有下属系，不能删除");
        }
    }

    @Override
    public boolean add(School school)throws SQLException{
        Connection connection = JdbcHelper.getConn();
        boolean added = schoolDaoImpl.add(connection,school);
        JdbcHelper.close(connection);
        return added;
    }


    public static void main(String[] args) throws SQLException, BysjException {
        Long id = 11L;
        System.out.println(SchoolDaoImpl.getInstance().find(id));
        SchoolServiceImpl.getInstance().delete(id);
        System.out.println(SchoolDaoImpl.getInstance().find(id));
    }
}

